package handlers

import (
	"ecom-admin/cache"
	"ecom-admin/models"
	"ecom-admin/pkg"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	var user models.User
	redis_key := "login_" + username
	errData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errData >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次，禁止登录",
		})
		return
	}
	err := models.DB.Where("username=?", username).Debug().First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	if pkg.Md5(password) != user.Password {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errData == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误3次，封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
	return
}
func RoleNode(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	if rid == 0 || nid == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := models.RoleNode{
		Rid: rid,
		Nid: nid,
	}
	models.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
		"data": data,
	})
	return
}
func UserRole(c *gin.Context) {
	/*
		SELECT
		*
		FROM
		roles
		LEFT JOIN user_roles ON roles.id=user_roles.uid
	*/
	uid := c.Query("uid")
	var role models.Role
	models.DB.Table("roles").
		Joins("LEFT JOIN user_roles ON roles.id=user_roles.uid").
		Where("user_roles.uid=?", uid).
		Debug().Find(&role)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": role,
	})
	return
}
func RolesNode(c *gin.Context) {
	/*
			SELECT
		*
		FROM
		nodes
		LEFT JOIN role_nodes ON nodes.id=role_nodes.rid
	*/
	rid := c.Query("rid")
	var node models.Node
	models.DB.Table("nodes").
		Joins("LEFT JOIN role_nodes ON nodes.id=role_nodes.rid").
		Where("role_nodes.rid=?", rid).
		Debug().Find(&node)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": node,
	})
	return
}
func CreateGoods(c *gin.Context) {
	goods_code := c.PostForm("goods_code")
	goods_name := c.PostForm("goods_name")
	goods_price := c.PostForm("goods_price")
	if goods_code == "" || goods_name == "" || goods_price == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := models.Goods{
		GoodsCode:  goods_code,
		GoodsName:  goods_name,
		GoodsPrice: goods_price,
	}
	models.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
		"data": data,
	})
	return
}
func CreateGoodsOrder(c *gin.Context) {
	gid, _ := strconv.Atoi(c.PostForm("gid"))
	order_code := c.PostForm("order_code")
	order_name := c.PostForm("order_name")
	if gid == 0 || order_code == "" || order_name == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := models.GoodsOrder{
		Gid:       gid,
		OrderCode: order_code,
		OrderName: order_name,
	}
	models.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
		"data": data,
	})
	return
}
func ListOrder(c *gin.Context) {
	/*
		SELECT
		  goods_orders.id OrderId,
		  goods_orders.order_code OrderCode,
		  goods_orders.order_name OrderName,
		  goods.goods_name GoodsName,
		  goods.goods_price GoodsPrice,
		  goods.created_at CreatedAt
		FROM
		goods_orders
		LEFT JOIN goods ON goods.id=goods_orders.gid
	*/
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	var order []models.GoodsOrderList
	redis_key := "list_order_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("goods_orders").
			Select("goods_orders.id OrderId,\n\t  goods_orders.order_code OrderCode,\n\t  goods_orders.order_name OrderName,\n\t  goods.goods_name GoodsName,\n\t  goods.goods_price GoodsPrice,\n\t  goods.created_at CreatedAt").
			Joins("LEFT JOIN goods ON goods.id=goods_orders.gid").
			Offset(offset).Limit(size).Debug().Find(&order)
		jsonData, _ := json.Marshal(&order)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &order)
	}
	var total int64
	models.DB.Model(&order).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  order,
		"total": total,
	})
	return
}
func DetailOrder(c *gin.Context) {
	/*
		SELECT
		  goods_orders.id OrderId,
		  goods_orders.order_code OrderCode,
		  goods_orders.order_name OrderName,
		  goods.goods_name GoodsName,
		  goods.goods_price GoodsPrice,
		  goods.created_at CreatedAt
		FROM
		goods_orders
		LEFT JOIN goods ON goods.id=goods_orders.gid
	*/
	id := c.Query("id")
	var order models.GoodsOrderList
	redis_key := "detail_order_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("goods_orders").
			Select("goods_orders.id OrderId,\n\t  goods_orders.order_code OrderCode,\n\t  goods_orders.order_name OrderName,\n\t  goods.goods_name GoodsName,\n\t  goods.goods_price GoodsPrice,\n\t  goods.created_at CreatedAt").
			Joins("LEFT JOIN goods ON goods.id=goods_orders.gid").
			Where("goods_orders.id=?", id).Debug().Find(&order)
		jsonData, _ := json.Marshal(&order)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &order)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ko",
		"data": order,
	})
	return
}
